package com.tyx.chargingpile.service.impl;

import com.tyx.chargingpile.Enum.ServiceExceptionEume;
import com.tyx.chargingpile.Enum.ServiceMessageEume;
import com.tyx.chargingpile.cache.SocketChannelMap;
import com.tyx.chargingpile.service.ChargingPileService;
import com.tyx.chargingpile.service.MessageService;
import com.tyx.chargingpile.service.exception.ServiceExcep;
import com.tyx.chargingpile.util.Util;
import com.tyx.chargingpile.vo.SocketResponseResult;
import io.netty.channel.ChannelHandlerContext;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 电价下发上行
 */
@Service("chargingPileElectricPriceUp")
public class ChargingPileElectricPriceUp implements ChargingPileService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ChargingPileElectricPriceUp.class);

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, byte[] context) throws Exception {
        Map<String,String> map = MessageService.analysisMessage(context, ServiceMessageEume.ELECTRICPRICE.getUpLinePath());
        checkData(map);
        String command = map.get("commandBack");
        String pileNum = SocketChannelMap.getDeviceId(channelHandlerContext.channel().id() + "");
        String commandId = ServiceMessageEume.ELECTRICPRICE.getCode();
        if (command.equals("FF")){
//            LOGGER.info("前置电价下发：桩编号--" + pileNum + ",成功" );
            LOGGER.info("客户端"+channelHandlerContext.channel().id().toString()+",指令控制编号："+commandId+",桩编号:" + pileNum + ",前置电价下发成功");

        }else {
            LOGGER.info("客户端"+channelHandlerContext.channel().id().toString()+",指令控制编号："+commandId+",桩编号:" + pileNum + ",前置电价下发失败");
        }
        return null;
    }

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, Map data) throws Exception {
        return null;
    }

    /**
     * 报文业务校验
     * @param map
     * @throws ServiceExcep
     */
    private void checkData(Map<String,String> map) throws ServiceExcep {
        if(map == null){
            throw new ServiceExcep(ServiceExceptionEume.MESSAGEPARSINGERROR);
        }
        String command = map.get("commandBack");
        if (TextUtils.isEmpty(command)){
            throw new ServiceExcep(ServiceExceptionEume.INCOMPLETEPARAMETERS);
        }
    }
}
